// pages/my/chat/index.js
const { messageAPI } = require('../../../utils/api');

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		msgList: [],
		pageNum: 1,
		pageSize: 15,
		hasMore: true,
		loading: false,
		ListTouchStart: 0,
		ListTouchDirection: null,
		modalName: null,
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		//获取消息列表
		this.getMegList();
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {
		this.loadMessageList(true);
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {
		this.loadMessageList(true);
		wx.stopPullDownRefresh();
	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {
		this.loadMessageList();
	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {

	},

	loadMessageList(refresh = false) {
		if (this.data.loading) return;
		if (!refresh && !this.data.hasMore) return;

		this.setData({ loading: true });

		const params = {
			pageNum: refresh ? 1 : this.data.pageNum,
			pageSize: this.data.pageSize
		};

		messageAPI.list(params).then(res => {
			const rawList = res.data.list || [];
			const currentGrouped = this.groupMessages(this.data.msgList);
			const newGrouped = this.groupMessages(rawList);

			// Merge new messages into existing conversations
			newGrouped.forEach(newItem => {
				const existingItemIndex = currentGrouped.findIndex(i => i.id === newItem.id);
				if (existingItemIndex > -1) {
					currentGrouped[existingItemIndex] = newItem;
				} else {
					currentGrouped.push(newItem);
				}
			});

			currentGrouped.sort((a,b) => new Date(b.rawTime) - new Date(b.rawTime));

			this.setData({
				msgList: currentGrouped,
				pageNum: params.pageNum + 1,
				hasMore: rawList.length === this.data.pageSize,
				loading: false
			});
		}).catch(err => {
			this.setData({ loading: false });
			wx.showToast({ title: err.message || '加载失败', icon: 'none' });
		});
	},

	groupMessages(messages) {
		const messageMap = new Map();
		messages.forEach(msg => {
			const key = msg.orderId;
			// Use createTime for sorting to find the latest message
			if (!messageMap.has(key) || new Date(msg.createTime) > new Date(messageMap.get(key).rawTime)) {
				messageMap.set(key, {
					id: msg.orderId,
					name: msg.lawyerName || '系统消息',
					avatar: msg.lawyerAvatar || '/static/images/avatar/user_none.png',
					msg: msg.content, // Use 'content'
					receiveTime: this.formatTime(msg.createTime),
					rawTime: msg.createTime, // Keep original time for sorting
					msgCount: msg.unreadCount || 0,
					orderId: msg.orderId,
				});
			}
		});
		return Array.from(messageMap.values());
	},

	formatTime(dateString) {
		const date = new Date(dateString);
		const hours = date.getHours().toString().padStart(2, '0');
		const minutes = date.getMinutes().toString().padStart(2, '0');
		return `${hours}:${minutes}`;
	},

	onChatItemTap(e) {
		const { orderid, lawyername } = e.currentTarget.dataset;
		wx.navigateTo({
			url: `/pages/my/chat/chatDetail?orderId=${orderid}&lawyerName=${lawyername}`,
		});
	},

	// ListTouch触摸开始
	ListTouchStart(e) {
		this.setData({ ListTouchStart: e.touches[0].pageX });
	},

	// ListTouch计算方向
	ListTouchMove(e) {
		this.setData({
			ListTouchDirection: e.touches[0].pageX - this.data.ListTouchStart > 0 ? 'right' : 'left'
		});
	},

	// ListTouch计算滚动
	ListTouchEnd(e) {
		if (this.data.ListTouchDirection == 'left') {
			this.setData({ modalName: e.currentTarget.dataset.target });
		} else {
			this.setData({ modalName: null });
		}
		this.setData({ ListTouchDirection: null });
	},

	/**
	 * 获取消息列表
	 */
	getMegList() {
		let that = this;
		let resData = [{
                id:1,
				name: "罗律师",
				msgCount: 5,
				avatar: "https://ossweb-img.qq.com/images/lol/web201310/skin/big81007.jpg",
				receiveTime: "22:30",
				msg: "是的",
				sendSuccess: true
			},
			{
                id:2,
				name: "顾律师",
				msgCount: 0,
				avatar: "https://ossweb-img.qq.com/images/lol/web201310/skin/big81007.jpg",
				receiveTime: "22:30",
				msg: "你好",
				sendSuccess: false
			},
			{
                id:3,
				name: "何律师",
				msgCount: 0,
				avatar: "https://ossweb-img.qq.com/images/lol/web201310/skin/big81007.jpg",
				receiveTime: "22:30",
				msg: "啊呀呀",
				sendSuccess: false
			},
			{
                id:4,
				name: "麦律师",
				msgCount: 0,
				avatar: "https://ossweb-img.qq.com/images/lol/web201310/skin/big81007.jpg",
				receiveTime: "22:30",
				msg: "我是",
				sendSuccess: false
			},
			{
                id:5,
				name: "戴律师",
				msgCount: 0,
				avatar: "https://ossweb-img.qq.com/images/lol/web201310/skin/big81007.jpg",
				receiveTime: "22:30",
				msg: "太好了",
				sendSuccess: false
			},

		]
		that.setData({
			msgList: resData
		})
	},
})
